//
//  UIView+Extension.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import UIKit

extension UIView {
    var left: CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            var rect = self.frame
            rect.origin.x = newValue
            self.frame = rect
        }
    }
    
    var top: CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            var rect = self.frame
            rect.origin.y = newValue
            self.frame = rect
        }
    }
    
    /// 右边界的x值
    var right: CGFloat {
        get {
            return self.left + self.width
        }
        set {
            var r = self.frame
            r.origin.x = newValue - frame.size.width
            self.frame = r
        }
    }
    
    var bottom: CGFloat {
        get {
            return self.top + self.height
        }
        set {
            var r = self.frame
            r.origin.y = newValue - frame.size.height
            self.frame = r
        }
    }
    
    var centerX : CGFloat {
        get {
            return self.center.x
        }
        set {
            self.center = CGPoint(x: newValue, y: self.center.y)
        }
    }

    var centerY : CGFloat {
        get {
            return self.center.y
        }
        set {
            self.center = CGPoint(x: self.center.x, y: newValue)
        }
    }
    
    var width: CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            var rect = self.frame
            rect.size.width = newValue
            self.frame = rect
        }
    }
    var height: CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            var rect = self.frame
            rect.size.height = newValue
            self.frame = rect
        }
    }
    
    var origin: CGPoint {
        get {
            return self.frame.origin
        }
        set {
            self.left = newValue.x
            self.top = newValue.y
        }
    }

    var size: CGSize {
        get {
            return self.frame.size
        }
        set {
            self.width = newValue.width
            self.height = newValue.height
        }
    }
}

enum SEDottedLineDirection {
    case vertical, horizontal
}

enum SEGradientColorDirection {
    case vertical, horizontal
}

extension UIView {
    /// 设置圆角
    func setLayerCorners(rect: CGRect, radius: CGFloat, corners: UIRectCorner = .allCorners) {
        if #available(iOS 11.0, *) {
            layer.cornerRadius = radius
            layer.maskedCorners = CACornerMask(rawValue: corners.rawValue)
        } else {
            let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer = CAShapeLayer()
            maskLayer.frame = rect
            maskLayer.path = path.cgPath
            layer.mask = maskLayer
        }
    }
    
    /// 绘制虚线
    /// - Parameters:
    ///   - lineWidth: 虚线宽度
    ///   - lineSpace: 虚线间隔
    ///   - lineColor: 虚线颜色
    ///   - direction: 虚线方向（水平/垂直）
    func drawDottedLine(lineWidth: CGFloat = 1.0,
                        lineSpace: Float = 2.0,
                        lineColor: UIColor = .gray,
                        direction: SEDottedLineDirection = .horizontal) {
        clipsToBounds = true
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = bounds
        
        shapeLayer.position = CGPoint(x: width / 2, y: height / 2)
        
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = lineColor.cgColor
        
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = .round
        shapeLayer.lineDashPhase = 0
        shapeLayer.lineDashPattern = [NSNumber(value: lineSpace), NSNumber(value: lineSpace)]
        
        let path = CGMutablePath()
        // 起点
        path.move(to: CGPoint(x: 0, y: 0))
        
        if direction == .horizontal {
            path.addLine(to: CGPoint(x: width, y: 0))
        } else {
            path.addLine(to: CGPoint(x: 0, y: height))
        }
        
        shapeLayer.path = path
        
        layer.addSublayer(shapeLayer)
    }
    
    /// 设置阴影
    func setShadow(color: UIColor = Asset.shadow.color,
                   radius: CGFloat = 5,
                   opacity: Float = 0.15,
                   offset: CGSize = .zero) {
        layer.shadowColor = color.cgColor
        layer.shadowOpacity = opacity
        layer.shadowRadius = radius
        layer.shadowOffset = offset
    }
    
    /// 背景支持渐变颜色
    func setGradientColor(_ colors: [UIColor]?, direction: SEGradientColorDirection = .horizontal, targetView: UIView? = nil) {
        // 外界如果改变了大小，需要先刷新
        layoutIfNeeded()
        
        removeGradientLayer()
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.locations = [0, 1]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = direction == .horizontal ? CGPoint(x: 1.0, y: 0.0) : CGPoint(x: 0.0, y: 1.0)
        gradientLayer.colors = colors?.compactMap { $0.cgColor }
        if let targetView = targetView {
            gradientLayer.frame = targetView.frame
            gradientLayer.cornerRadius = targetView.layer.cornerRadius
        } else {
            gradientLayer.frame = bounds
            gradientLayer.cornerRadius = layer.cornerRadius
        }
        gradientLayer.masksToBounds = true
        layer.insertSublayer(gradientLayer, at: 0)
    }
    
    /// 移除渐变图层
    func removeGradientLayer() {
        if let sublayers = layer.sublayers {
            for layer in sublayers {
                if layer.isKind(of: CAGradientLayer.self) {
                    layer.removeFromSuperlayer()
                }
            }
        }
    }
}

extension UIView {
    static func nibForCell() -> UINib {
        return UINib(nibName: String(describing: self), bundle: nil)
    }
    
    static func reuseIdentifier() -> String {
        return String(describing: self) + "ID"
    }
}
